-- HealthBar.lua (使用DrawNode的正确API)
local HealthBar = {}
HealthBar.__index = HealthBar

function HealthBar.new(options)
    options = options or {}
    
    local instance = {
        width = options.width or 200,
        height = options.height or 24,
        currentHealth = 100,
        maxHealth = 100,
        uiNode = nil,
        textNode = nil,
        healthDrawNode = nil,
        bgDrawNode = nil,
        borderDrawNode = nil,
        targetNode = nil,
        offsetX = 0,
        offsetY = 0
    }
    
    return setmetatable(instance, HealthBar)
end

function HealthBar:create()
    local Node = require("Node")
    local Size = require("Size")
    local Vec2 = require("Vec2")
    local DrawNode = require("DrawNode")
    local Color = require("Color")
    
    print("创建血条...")
    
    -- 创建根节点
    self.uiNode = Node()
    self.uiNode.visible = true
    self.uiNode.touchEnabled = false
    self.uiNode.zOrder = 1000
    self.uiNode.size = Size(self.width, self.height)
    
    if not DrawNode or not Color then
        print("DrawNode或Color模块不可用")
        return self.uiNode
    end
    
    -- 创建背景DrawNode（使用drawPolygon）
    self.bgDrawNode = DrawNode()
    local bgColor = Color(30, 30, 30, 220)  -- 深灰色背景
    
    local bgVerts = {
        Vec2(0, 0),
        Vec2(self.width, 0),
        Vec2(self.width, self.height),
        Vec2(0, self.height)
    }
    
    self.bgDrawNode:drawPolygon(bgVerts, bgColor)
    self.uiNode:addChild(self.bgDrawNode)
    print("✓ 绘制背景")
    
    -- 创建血量DrawNode
    self.healthDrawNode = DrawNode()
    self.uiNode:addChild(self.healthDrawNode)
    print("✓ 创建血量条节点")
    
    -- 创建边框DrawNode（使用drawSegment绘制4条线）
    self.borderDrawNode = DrawNode()
    local borderColor = Color(255, 255, 255, 200)
    
    -- 绘制4条边线
    self.borderDrawNode:drawSegment(Vec2(0, 0), Vec2(self.width, 0), 1, borderColor) -- 上边
    self.borderDrawNode:drawSegment(Vec2(self.width, 0), Vec2(self.width, self.height), 1, borderColor) -- 右边
    self.borderDrawNode:drawSegment(Vec2(self.width, self.height), Vec2(0, self.height), 1, borderColor) -- 下边
    self.borderDrawNode:drawSegment(Vec2(0, self.height), Vec2(0, 0), 1, borderColor) -- 左边
    
    self.uiNode:addChild(self.borderDrawNode)
    print("✓ 绘制边框")
    
    -- 创建文本
    self:createText()
    
    -- 初始更新血量显示
    self:updateHealth(self.currentHealth, self.maxHealth)
    
    print("血条创建完成")
    return self.uiNode
end

function HealthBar:createText()
    local Label = require("Label")
    local Vec2 = require("Vec2")
    local Color = require("Color")
    
    if not Label then
        print("Label模块不可用")
        return
    end
    
    -- 尝试不同的字体，字体大小14
    local label
    local success = false
    
    -- 方法1：Xolonium-Regular，字体大小14
    success, label = pcall(function()
        return Label("Xolonium-Regular", 20)
    end)
    
    -- 方法2：sarasa-mono-sc-regular，字体大小14
    if not success then
        success, label = pcall(function()
            return Label("sarasa-mono-sc-regular", 20)
        end)
    end
    
    -- 方法3：默认字体，字体大小14
    if not success then
        success, label = pcall(function()
            return Label(20)  -- 字体大小改为14
        end)
    end
    
    -- 方法4：无参数
    if not success then
        success, label = pcall(Label)
    end
    
    if success and label then
        self.textNode = label
        self.textNode.text = string.format("%d/%d", math.floor(self.currentHealth), self.maxHealth)
        
        if Color then
            self.textNode.color = Color(255, 255, 255, 255)
        end
        
        self.textNode.position = Vec2(self.width / 2, self.height / 2)
        self.textNode.anchor = Vec2(0.5, 0.5)
        self.uiNode:addChild(self.textNode)
        print("✓ 创建血量文本成功（字体大小: 25）")
    else
        print("✗ 所有Label创建方式都失败")
    end
end

function HealthBar:updateHealth(current, max)
    local DrawNode = require("DrawNode")
    local Vec2 = require("Vec2")
    local Color = require("Color")
    
    if not DrawNode or not Color then
        return
    end
    
    current = current or 0
    max = max or 100
    
    if current < 0 then current = 0 end
    if max <= 0 then max = 100 end
    
    self.currentHealth = current
    self.maxHealth = max
    local percentage = max > 0 and (current / max) or 0
    
    -- 更新血量条（使用drawPolygon）
    if self.healthDrawNode and self.healthDrawNode.clear then
        self.healthDrawNode:clear()
        
        local healthWidth = self.width * percentage
        
        if healthWidth > 0 then  -- 只有血量大于0时才绘制
            -- 根据血量选择颜色
            local healthColor
            if current <= 0 then
                healthColor = Color(128, 128, 128, 255)  -- 灰色（死亡）
            elseif percentage < 0.3 then
                healthColor = Color(255, 200, 50, 255)   -- 黄色（低血量）
            else
                healthColor = Color(50, 200, 50, 255)    -- 绿色（健康）
            end
            
            -- 使用drawPolygon绘制血量矩形
            local verts = {
                Vec2(0, 0),
                Vec2(healthWidth, 0),
                Vec2(healthWidth, self.height),
                Vec2(0, self.height)
            }
            
            self.healthDrawNode:drawPolygon(verts, healthColor)
        end
    end
    
    -- 更新文本
    if self.textNode then
        self.textNode.text = string.format("%d/%d", current, max)
        
        if Color then
            -- 根据血量改变文本颜色
            if current <= 0 then
                self.textNode.color = Color(200, 200, 200, 255)
            elseif percentage < 0.3 then
                self.textNode.color = Color(255, 255, 100, 255)
            else
                self.textNode.color = Color(255, 255, 255, 255)
            end
        end
    end
    
    print(string.format("血量更新: %d/%d (%.1f%%)", current, max, percentage * 100))
end

function HealthBar:setFollowTarget(targetNode, offsetX, offsetY)
    if not targetNode or not self.uiNode then 
        print("设置跟随目标失败")
        return false
    end
    
    local Vec2 = require("Vec2")
    
    offsetX = offsetX or 0
    offsetY = offsetY or 0
    
    -- 如果已经有父节点，先移除（不清理）
    if self.uiNode.parent then
        self.uiNode:removeFromParent(false)  -- cleanup=false
    end
    
    -- 添加到目标节点
    targetNode:addChild(self.uiNode)
    
    -- 设置相对位置
    self.uiNode.position = Vec2(offsetX, offsetY)
    
    -- 确保在最上层
    self.uiNode.zOrder = 1000
    
    return true
end

function HealthBar:cleanup()
    if self.uiNode then
        -- 彻底清理节点
        self.uiNode:removeFromParent(true)  -- cleanup=true
        self.uiNode:cleanup()
        self.uiNode = nil
    end
end

return HealthBar